//提供复用逻辑
import { useIntersectionObserver } from "@vueuse/core";
import { ref, onUnmounted } from "vue";
import dayjs from "dayjs";
import { useIntervalFn } from "@vueuse/shared";

/**
 *
 * @param {Element} target Dom对象
 * @param {Function} apiFn API网络请求函数
 */
export const useLazyData = (apiFn) => {
  const target = ref(null);
  const data = ref([]);
  //stop停止观察
  const { stop } = useIntersectionObserver(
    //监听的目标元素
    //isIntersecting是否进入可视区,true是进入 false是移出
    // observerElement 被观察的dom
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop();
        apiFn().then((res) => {
          data.value = res.result;
        });
      }
    },
    {
      //相交比例，碰到就直接触发，而不是像当盒子很大时候，需要移动很大一部分才加载。0-1 之间，默认比0大
      threshold: 0,
    }
  );
  return {
    target,
    data,
  };
};

export const usePayTime = () => {
  //倒计时函数
  const time = ref(0);
  const timeText = ref("");
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--;
      timeText.value = dayjs.unix(time.value).format("mm分ss秒");
      if (time.value <= 0) {
        pause();
      }
    },
    1000,
    false
  );
  onUnmounted(() => {
    pause();
  });
  const start = (countdown) => {
    time.value = countdown;
    timeText.value = dayjs.unix(time.value).format("mm分ss秒");
    resume();
  };

  return { start, timeText, time };
};
